package com.xiashitech.agent.instrumentation.httprequest.utils;

import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.utils.JsonUtil;
import com.xiashitech.interfaces.agent.dto.AgentConfigDTO;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Map;

public class RequestInfoUtil {
    /**
     * 从request中提取用户信息
     * 1、post方式的话从body中提取
     */
    public static void extractLoginName(Object request, UserRequest userRequest) {
        try {
            String loginPathKey = null;
            Map<String, String> loginPathKeyMap = AgentConfigDTO.getConfig().getLoginPath();
            if (loginPathKeyMap != null){
                loginPathKey = loginPathKeyMap.get(StartConfig.getParamValueFromKey(StartConfig.systemId));
            }
            String loginNameKey = null;
            Map<String,String> loginNameKeyMap = AgentConfigDTO.getConfig().getLoginName();
            if (loginNameKeyMap != null){
                loginNameKey =  loginNameKeyMap.get(StartConfig.getParamValueFromKey(StartConfig.systemId));
            }
            if(request instanceof HttpServletRequest && ((HttpServletRequest)request).getContentType() != null && ((HttpServletRequest)request).getContentType().toLowerCase().contains("json") && loginPathKey != null && ((HttpServletRequest)request).getRequestURI().contains(loginPathKey)) {
                InputStream inputStream = ((HttpServletRequest)request).getInputStream();
                Map<String,Object> bodyMap = JsonUtil.getMapFromInputStream(inputStream);
                if(bodyMap.containsKey(loginNameKey)) {
                    userRequest.setLoginName(bodyMap.get(loginNameKey).toString());
                }
            }
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
    }
}
